package com.braska.hewankurban;

import org.json.JSONArray;
import org.json.JSONObject;

import com.braska.hewankurban.helper.ServiceHelper;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	ServiceHelper srv = new ServiceHelper();
	EditText uname, pass;
	String u, p;
	String id_user;
	Intent i;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		Button btnLogin = (Button) findViewById(R.id.btnLogin);
		uname = (EditText) findViewById(R.id.inputUsr);
		pass = (EditText) findViewById(R.id.inputPass);

		btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				u = uname.getText().toString();
				p = pass.getText().toString();

				new LoginTask().execute();
			}
		});

	}

	public class LoginTask extends AsyncTask<String, Void, Boolean> {

		ProgressDialog dialog = new ProgressDialog(LoginActivity.this);

		protected void onPreExecute() {
			dialog.setMessage(" Login ");
			dialog.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				String srves = srv.getuser(uname.getText().toString());
				Log.i("alakazam", srves);
				try {

					JSONArray ja = new JSONArray("[" + srves + "]");
					JSONArray innerJSONArray = ja.getJSONArray(0);
					JSONObject json = innerJSONArray.getJSONObject(0);
					Log.d("anunedowoooobangettttt", innerJSONArray.length()
							+ "");

					for (int i = 0; i < innerJSONArray.length(); i++) {
						JSONObject j = innerJSONArray.getJSONObject(i);
						id_user = j.getString("id_user");
					}

					Log.i("id", id_user);

				} catch (Exception e) {
					// TODO: handle exception
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
			if (srv.login(u, p) == true) {
				return true;
			} else {
				return false;
			}
		}

		protected void onPostExecute(Boolean result) {
			dialog.dismiss();

			if (result == true) {
				Toast.makeText(LoginActivity.this, "Login Success",
						Toast.LENGTH_LONG).show();
				i = new Intent(getApplicationContext(), BiodataActivity.class);
				i.putExtra("id", id_user);
				startActivity(i);
				finish();

			} else {

				Toast.makeText(LoginActivity.this, "Login Failed",
						Toast.LENGTH_LONG).show();
			}

		}

	}

}
